package com.lyf.boot.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lyf.boot.base.system.dao.BaseSysClientDao;
import com.lyf.boot.base.system.entity.SysClient;
import com.lyf.boot.modules.system.entity.dto.SysClientDto;
import com.lyf.boot.modules.system.entity.vo.SysClientVo;
import com.lyf.boot.modules.system.service.ISysClientService;
import com.lyf.boot.utils.MapstructUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Luyufan
 * @date 2024/1/11 09:50
 **/
@Service
@RequiredArgsConstructor
public class SysClientServiceImpl implements ISysClientService {

    private final BaseSysClientDao baseSysClientDao;

    @Override
    public List<SysClientVo> getSysClientList() {
        List<SysClient> list = baseSysClientDao.selectList(Wrappers.<SysClient>lambdaQuery().orderByDesc(SysClient::getUpdateTime));
        if(CollUtil.isEmpty(list)){
            return CollUtil.toList();
        }
        //TODO 使用mapstruct
        return MapstructUtil.convert(list, SysClientVo.class);
        //return BeanUtil.copyToList(list, SysClientVo.class);
    }

    @Override
    public SysClient getSysClientByCoe(String clientCode) {
        return baseSysClientDao.getSysClientByCode(clientCode);
    }

    @Override
    public SysClientVo getSysClientById(Long clientId) {
        SysClient sysClient = baseSysClientDao.selectById(clientId);
        if(null == sysClient){
            return null;
        }
        return MapstructUtil.convert(sysClient, SysClientVo.class);
        //return BeanUtil.copyProperties(sysClient, SysClientVo.class);
    }

    @Override
    public void saveSysClient(SysClientDto dto) {
        SysClient sysClient = MapstructUtil.convert(dto, SysClient.class);
        String clientKey = sysClient.getClientKey();
        String clientSecret = sysClient.getClientSecret();
        String clientCode = SecureUtil.md5(clientKey + clientSecret);
        sysClient.setClientCode(clientCode);
        baseSysClientDao.insert(sysClient);
    }

    @Override
    public void updateSysClient(SysClientDto dto) {
        SysClient sysClient = MapstructUtil.convert(dto, SysClient.class);
        String clientKey = sysClient.getClientKey();
        String clientSecret = sysClient.getClientSecret();
        String clientCode = SecureUtil.md5(clientKey + clientSecret);
        sysClient.setClientCode(clientCode);
        baseSysClientDao.updateById(sysClient);
    }

    @Override
    public void deleteSysClient(List<Long> ids) {
        baseSysClientDao.deleteByIds(ids);
    }
}
